import { devConfig } from '../config.js';
import shell from 'shelljs';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import path from 'path';
import SFTPClient from 'ssh2-sftp-client'; // 使用默认导出

// 通过 fileURLToPath 和 dirname 模拟 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 打包 npm run build
const compileDist = async () => {
  if (shell.exec('npm run build:stage').code === 0) {
    console.log('打包成功');
  }
};

async function connectSSh() {
  const sftp = new SFTPClient(); // 使用 SFTPClient 来实例化
  try {
    await sftp.connect({
      host: devConfig.ip,
      port: devConfig.port,
      username: devConfig.username,
      password: devConfig.password
    });

    // 检查目录是否存在
    const exists = await sftp.exists(devConfig.rmpath);
    if (exists) {
      console.log('先执行删除服务器文件');
      await sftp.rmdir(devConfig.rmpath, true);
    }

    // 上传文件
    console.log('开始上传');
    let totalFiles = 0;
    let uploadedFiles = 0;
    sftp.on('upload', info => {
      uploadedFiles++;
      const progress = Math.floor((uploadedFiles / totalFiles) * 100);
      process.stdout.write(`上传进度: ${progress}% [${uploadedFiles}/${totalFiles}]\r`);
    });
    // 先获取总文件数
    const countFiles = (dir) => {
      const files = shell.ls('-R', dir);
      return files.length;
    };
    totalFiles = countFiles(path.resolve(__dirname, '../../dist'));
    await sftp.uploadDir(path.resolve(__dirname, '../../dist'), devConfig.path);
    console.log('上传完成,开始拷贝至运行目录');

  } catch (err) {
    console.log(err, '失败');
  } finally {
    sftp.end();
  }
}

async function runTask() {
  try {
    await compileDist(); // 打包完成
    await connectSSh(); // 提交上传至个人目录
  } catch (err) {
    console.error('任务执行失败:', err);
  }
}

runTask();
